package com.chen.filter;

import com.chen.utils.CurrentHolder;
import com.chen.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        先进行强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;//强转http请求
        HttpServletResponse response = (HttpServletResponse) servletResponse;//强转http响应
        //1.获取请求路径
        String path = request.getRequestURI(); //获取请求路径
        //2.判断是否为登陆路径
        if(path.contains("/login")) {
            log.info("登陆请求，放行");
            filterChain.doFilter(request,response);
            return;
        }
            //3.获取请求头中的token
        String token = request.getHeader("token");
        //4.判断token是否存在，如果不存在则返回给前端401响应码
        if(token == null || token.isEmpty()) {
            log.info("令牌为空，返回401响应码");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //5.令牌如果存在则解析令牌，进行校验令牌，如果校验失败则返回401响应码
        try {
            Claims claims = JwtUtils.parseToken(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);//放入线程
            log.info("当前员工id为{},并存入ThreadLocal",empId);

        } catch (Exception e) {
            log.info("令牌校验失败，返回401响应码");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
        //6.如果校验成功则放行
        log.info("令牌合法，放行");
        filterChain.doFilter(request,response);
        //7.最后清空线程
        CurrentHolder.remove();
    }
}
